package com.xhji.web.mvc.interceptor;

import com.alibaba.fastjson.JSON;
import com.xhji.web.mvc.response.DefaultGenericResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截验证
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor, WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    /**
     * 登录拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(this)
//                .addPathPatterns("/**")
//                .excludePathPatterns("index","/login","/views/**");
    }

    /**
     * 登录session key
     */
    public final static String SESSION_KEY = "user";

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) {

    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String hl = handler.toString();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        String uri = request.getRequestURI();
        //登录放行
        if ("/vcodelogin".equals(uri)||"/login".equals(uri)) {
            return true;
        }
        //重定向
        Object object = request.getSession().getAttribute(SESSION_KEY);
        System.out.println(JSON.toJSONString(object));
        if (null == object) {
            System.out.println("已拦截："+uri);
            request.getSession().setAttribute("preuri", uri);
            DefaultGenericResponse<Object> re = new DefaultGenericResponse<>();
            re.setCode(HttpStatus.UNAUTHORIZED.value());
            re.setMessage("用户参数非法,请确认登录状态");
            response.getOutputStream().write(JSON.toJSONBytes(re));
            return false;
        }
        return true;
    }

}
